package com.maben.security.filter;

import com.maben.security.util.RedisTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 使用redis对token进行过滤
 */
@Slf4j
public class RedisTokenFilter extends OncePerRequestFilter {

    private final  RedisTokenUtils tokenUtils;
    private final UserDetailsService userServiceImpl;

    public RedisTokenFilter(RedisTokenUtils tokenUtils, UserDetailsService userServiceImpl) {
        this.tokenUtils = tokenUtils;
        this.userServiceImpl = userServiceImpl;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        // 1. 从请求头获取Token（格式：Bearer <token>）
        String authHeader = request.getHeader("Authorization");
        String token = null;
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        }
        log.info("请求路径：{}", request.getRequestURI());
        // 2. 验证Token并获取用户名
        if (token != null) {
            String username = tokenUtils.validateToken(token);
            // 3. 若Token有效且未认证，则设置认证信息
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 3.1 加载用户详情（从数据库/缓存）
                UserDetails userDetails = userServiceImpl.loadUserByUsername(username);
                // 3.2 创建认证对象（已认证状态）
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities()
                );
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 3.3 设置到安全上下文
                SecurityContextHolder.getContext().setAuthentication(authToken);
                // 3.4 动态续期（用户持续操作，延长Token有效期）
                tokenUtils.renewToken(token);
            }
        }

        // 继续执行后续过滤器
        filterChain.doFilter(request, response);
    }
}